/**
 * Created by linyi on 2019/3/5
 */
import axios from 'axios'
import Hosts from 'ApiHost'

export const ORIGINAL_RESP = '__original_response__'

const formatter = (obj = {}) =>
  Object.entries(obj).reduce(
    (acc, [k, v]) =>
      Array.isArray(v) ? { ...acc, [k]: v.join(',') } : { ...acc, [k]: v },
    {}
  )

export default (function() {
  let loginToken = localStorage.getItem('login-token') || ''

  return async ({ host, schema }, method, config = {}) => {
    const { data: postData, params, headers: passedHeaders, ...passed } = config

    const response = await axios.request({
      url: Hosts[host] + schema,
      method,
      headers: {
        'login-token': loginToken,
        ...passedHeaders
      },
      data: formatter(postData),
      params: formatter(params),
      ...passed
    })

    const { status, data, headers } = response

    if (headers['login-token']) {
      loginToken = headers['login-token']
      localStorage.setItem('login-token', headers['login-token'])
    }

    if (status !== 200) {
      return Promise.reject(Error('请求失败'))
    }

    switch (data.code) {
      case 200000:
        return { ...data, [ORIGINAL_RESP]: response }
      case 600201: // 未登录或登录过期
      case 600207:
        window.location.replace(
          `/login?next=${encodeURIComponent(window.location.pathname)}`
        )
        return Promise.reject(data.message)
      default:
        return Promise.reject(data.message)
    }
  }
})()
